#!/usr/bin/env python
# coding=utf-8

import json
import sys
import fcntl
import os
from functools import wraps


class action(object):
    action_method = {}

    def __init__(self, name):
        self.name = name

    def __call__(self, f):
        action.action_method[self.name] = f
        return f


@action('add')
def add(config, port, password):
    port_password = config.get('port_password', {})
    port_password[str(port)] = password
    config['port_password'] = port_password
    return config


@action('remove')
def remove(config, port, password):
    port_password = config.get('port_password')

    found = None
    for p in port_password:
        strip_p = p.strip()
        if port == strip_p:
            found = p
            break

    if port_password.get(found) == password:
        del port_password[p]

    config['port_password'] = port_password
    return config


class Lock(object):
    def __init__(self, filename='/opt/ss/change_account.lock'):
        self.lock = open(filename, 'w')

    def __enter__(self):
        fcntl.flock(self.lock.fileno(), fcntl.LOCK_EX)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        fcntl.flock(self.lock.fileno(), fcntl.LOCK_UN)
        self.lock.close()

        return False


def main():
    data = sys.stdin.read()
    result = json.loads(data)

    port = result.get('port')
    password = result.get('password')

    with Lock() as lock:
        ss = '/opt/ss/config.json'

        with open(ss) as fp:
            config = json.load(fp)
            method = action.action_method[result.get('action')]
            config = method(config, port, password)

        with open(ss, 'w') as fp:
            json.dump(config, fp, indent=4)


if __name__ == '__main__':
    main()
